<!-- 产品碳足迹-产品碳足迹-产品核算-模型搭建-输入输出表单 -->

<template>
  <div>
    <a-drawer
      :body-style="{ paddingBottom: '80px' }"
      :title="drawerTitle"
      :visible="visible"
      :width="700"
      @close="onClose"
    >
      <a-tabs :activeKey="activeKey" @change="onChangeActiveKey">
        <a-tab-pane key="1" forceRender :tab="$t('message.Basic_information')">
          <a-form-model
            :label-col="labelCol"
            :model="formObj"
            :wrapper-col="wrapperCol"
            labelAlign="left"
          >
            <a-form-model-item :label="$t('message.Name')" required>
              <a-input
                v-model="formObj.emissionSourceName"
                :disabled="disabled"
                allowClear
                :placeholder="$t('message.Please_enter')"
              ></a-input>
            </a-form-model-item>

            <a-form-model-item :label="$t('message.Type')" required>
              <a-select
                v-model="formObj.emissionSourceType"
                :disabled="disabled"
                :filter-option="filterOption"
                allowClear
                :placeholder="$t('message.Please_select')"
                show-search
                style="width: 100%"
                @change="onChangeFlowType"
              >
                <a-select-option
                  v-for="(item, index) in product_typeData"
                  :key="index"
                  :value="item.value"
                >
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-model-item>

            <!-- <a-form-model-item :label="$t('message.Number')" required>
              <a-select v-model="formObj.flowType" :disabled="disabled" :filter-option="filterOption" allowClear
                        :placeholder="$t('message.Please_select')" show-search style="width: 100%;" @change="onChangeFlowType">
                <a-select-option v-for="(item,index) in product_typeData" :key="index" :value="item.value">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-model-item> -->

            <a-form-model-item :label="$t('message.Unit')" required>
              <a-select
                v-model="formObj.emissionSourceUnit"
                :disabled="disabled"
                allowClear
                :placeholder="$t('message.Please_select')"
                @change="onChangeFlowUnit"
              >
                <a-select-opt-group
                  :key="key"
                  :value="key"
                  :label="key"
                  v-for="(value, key, index) in getAllUnitByGroupData"
                >
                  <a-select-option
                    :key="itemA.id"
                    :value="itemA.id"
                    v-for="(itemA, indexA) in value"
                  >
                    {{ itemA.unitCode }}
                  </a-select-option>
                </a-select-opt-group>
              </a-select>
            </a-form-model-item>

            <a-form-model-item :label="$t('message.Data_source')" required>
              <a-select
                v-model="formObj.dataSources"
                :disabled="disabled"
                :filter-option="filterOption"
                allowClear
                :placeholder="$t('message.Please_select')"
                show-search
                @change="onChangeFlowDataSources"
              >
                <a-select-option
                  v-for="(item, index) in flow_data_sourcesData"
                  :key="index"
                  :value="item.value"
                >
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-model-item>

            <!-- <a-form-model-item :label="$t('message.Data_certificate')" required>
              <div class="butons">
                <img src="@/assets/cptzj/img5.png" alt="">
                上传附件
              </div>
              <div class="textse">{{$t('message.Only_pdf_png_jpg_and_peg_formats_are_supported_for_upload_with_a_maximum_of_one_file_The_size_of_each_file_should_not_exceed_5M')}}</div>
            </a-form-model-item> -->

            <a-form-model-item :label="$t('message.Emission_factor')" required>
              <div v-if="!formObj.emissionFactorId" class="tianjia">
                <div class="color">{{ $t("message.please_add_factor") }}</div>
                <div>
                  <a-button
                    class="leftShoudong"
                    icon="plus"
                    @click="handleAdd('addYZ')"
                    >{{ $t("message.Manually_add") }}</a-button
                  >
                  <a-button
                    class="leftChaxun"
                    icon="plus"
                    @click="handleAdd('chooseYZ')"
                    >{{ $t("message.Select_factor") }}</a-button
                  >
                </div>
              </div>
              <div v-else>
                <yzCard :item="selectedRows" />
                <div v-if="!disabled" class="manual">
                  <div
                    class="manualOperation m_hoverCP"
                    @click="handleAdd('addYZ')"
                  >
                    <img alt="" src="@/assets/carbon/img9.png" />{{
                      $t("message.Manually_add")
                    }}
                  </div>
                  <div
                    class="manualOperation m_hoverCP"
                    @click="handleAdd('chooseYZ')"
                  >
                    <img alt="" src="@/assets/carbon/img10.png" />{{
                      $t("message.Select_again")
                    }}
                  </div>
                </div>
              </div>
            </a-form-model-item>

            <a-form-model-item required>
              <span slot="label">
                {{ $t("message.Unit_proportional_conversion") }}
                <a-tooltip
                  :title="
                    $t(
                      'message.The_conversion_of_activity_data_units_to_factor_denominator_units_for_example_1t1000kg'
                    )
                  "
                >
                  <a-icon type="question-circle-o" />
                </a-tooltip>
              </span>
              <div class="box1">
                <div class="fleWarp">
                  <div class="box1_text1">
                    1{{ formObj.emissionSourceUnitName }}
                  </div>
                  <div class="box1_text2">
                    （{{ $t("message.Active_data_unit") }}）
                  </div>
                </div>
                <div class="box1_text3">=</div>
                <a-input-number
                  v-model="formObj.factorRatio"
                  :disabled="disabled"
                  allowClear
                  :placeholder="$t('message.Please_enter')"
                  style="width: 100px; margin-right: 4px"
                ></a-input-number>
                <div class="fleWarp">
                  <div class="box1_text1">
                    {{formObj.emissionFactorId ? selectedRows.denominatorUnit : "" }}
                  </div>
                  <div class="box1_text2">
                    （{{ $t("message.Factor_denominator_unit") }}）
                  </div>
                </div>
              </div>
            </a-form-model-item>
          </a-form-model>
        </a-tab-pane>
        <a-tab-pane key="2" forceRender :tab="$t('message.Transport_information')">
          <a-form-model :label-col="labelCol" :model="formObj" :wrapper-col="wrapperCol" labelAlign="left">
            <a-form-model-item :label="$t('message.Need_or_no_need_transportation')" required>
              <a-radio-group v-model="formObj.isTransport" :disabled="disabled" button-style="solid"
                             @change="onChangeIsTransport">
                <a-radio-button :value="false">{{$t('message.No_need_to_transport')}}</a-radio-button>
                <a-radio-button :value="true">{{$t('message.Need_transportation')}}</a-radio-button>
              </a-radio-group>
            </a-form-model-item>
            <a-form-model-item
              v-if="formObj.isTransport"
              :label="$t('message.Unit_of_weight_of_goods')"
              required
            >
              <a-select
                v-model="formObj.weightUnit"
                :disabled="disabled"
                :filter-option="filterOption"
                allowClear
                :placeholder="$t('message.please_select_unit')"
                show-search
                style="width: 41%;margin-right: 24px;"
                @change="onChangeWeightUnit"
              >
                <a-select-option
                  v-for="(item, index) in unit_product_weightData"
                  :key="index"
                  :value="item.id"
                >
                  {{ item.unitCode }}
                </a-select-option>
              </a-select>
              <a-input-number v-model="qianm" :disabled="true" :precision="2" :step="0.01"
                              allowClear :placeholder="$t('message.Please_enter')" style="width: 41%;"/>
              <div style="width: 2%;display: inline-block"></div>
            </a-form-model-item>
          </a-form-model>
          <template v-if="formObj.isTransport">
            <a-collapse v-model="activeCollapseKey" :bordered="false">
              <template #expandIcon="props">
                <img
                  v-if="props.isActive"
                  alt=""
                  class="collapseIcon"
                  src="@assets/img/img47.png"
                />
                <img
                  v-else
                  alt=""
                  class="collapseIcon"
                  src="@assets/img/img46.png"
                />
              </template>
              <a-collapse-panel
                v-for="(transportItem, transportIndex) in formObj.transportList"
                :key="String(transportIndex)"
                :header="$t('message.Road_section') + (transportIndex + 1)"
              >
                <img
                  v-if="transportIndex > 0"
                  slot="extra"
                  alt=""
                  class="collapseIcon"
                  src="@assets/img/img33.png"
                  @click="onDelTransport(transportIndex)"
                />
                <a-form-model
                  :label-col="labelCol"
                  :model="formObj"
                  :wrapper-col="wrapperCol"
                  labelAlign="left"
                >
                  <a-form-model-item
                    :label="$t('message.Means_of_transportation')"
                    required
                  >
                    <a-select
                      v-model="transportItem.vehicleId"
                      :disabled="disabled"
                      :filter-option="filterOption"
                      allowClear
                      :placeholder="$t('message.Please_select')"
                      show-search
                      @change="onChangeVehicleId($event, transportItem)"
                    >
                      <a-select-option
                        v-for="(item, index) in vehicle_codeData"
                        :key="index"
                        :value="item.value"
                      >
                        {{ item.text }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                  <!-- <a-form-model-item :label="`${$t('message.Distance')}(km)`" required>
                    <a-select v-model="transportItem.vehicleId" :disabled="disabled" :filter-option="filterOption"
                              allowClear :placeholder="$t('message.Please_select')" show-search @change="onChangeVehicleId($event,transportItem)">
                      <a-select-option v-for="(item,index) in vehicle_codeData" :key="index" :value="item.value">
                        {{ item.text }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item> -->
                  <a-form-model-item
                    :label="$t('message.Emission_factor')"
                    required
                  >
                    <div v-if="!transportItem.emissionFactorId" class="tianjia">
                      <div class="color">
                        {{ $t("message.please_add_factor") }}
                      </div>
                      <div v-if="!disabled">
                        <a-button
                          class="leftShoudong"
                          icon="plus"
                          @click="handleAdd('addYZ', transportIndex)"
                          >{{ $t("message.Manually_add") }}
                        </a-button>
                        <a-button
                          class="leftChaxun marRight"
                          icon="plus"
                          @click="handleAdd('chooseYZ', transportIndex)"
                        >
                          {{ $t("message.Select_factor") }}
                        </a-button>
                      </div>
                    </div>
                    <div v-else>
                      <yzCard :item="transportItem.selectedRows" />
                      <div v-if="!disabled" class="manual">
                        <div
                          class="manualOperation m_hoverCP"
                          @click="handleAdd('addYZ', transportIndex)"
                        >
                          <img alt="" src="@/assets/carbon/img9.png" />{{
                            $t("message.Manually_add")
                          }}
                        </div>
                        <div
                          class="manualOperation m_hoverCP"
                          @click="handleAdd('chooseYZ', transportIndex)"
                        >
                          <img alt="" src="@/assets/carbon/img10.png" />{{
                            $t("message.Select_again")
                          }}
                        </div>
                      </div>
                    </div>
                  </a-form-model-item>
                  <a-form-model-item
                    :label="$t('message.Unit_proportional_conversion')"
                    required
                  >
                    <div class="box1">
                      <div class="fleWarp">
                        <div class="box1_text1">
                        1{{ formObj.weightUnitName }}*{{qianm}}
                      </div>
                      <div class="box1_text2">
                        （{{ $t("message.Active_data_unit") }}）
                      </div>
                      </div>
                     
                      <div class="box1_text3">=</div>
                      <a-input-number
                        v-model="transportItem.factorRatio"
                        :disabled="disabled"
                        allowClear
                        :placeholder="$t('message.Please_enter')"
                        style="width: 100px; margin-right: 4px"
                      ></a-input-number>
                      <div class="fleWarp">
                        <div class="box1_text1" v-if="transportItem.selectedRows">
                          {{
                            transportItem.emissionFactorId
                              ? transportItem.selectedRows.denominatorUnit
                              : ""
                          }}
                        </div>
                        <div class="box1_text2">
                          （{{ $t("message.Factor_denominator_unit") }}）
                        </div>
                      </div>
                    </div>
                  </a-form-model-item>
                </a-form-model>
              </a-collapse-panel>
            </a-collapse>
            <div
              v-if="!disabled"
              class="addBtn m_hoverCP"
              @click="onAddTransport"
            >
              <img alt="" class="addBtn_icon" src="@assets/img/img30.png" />{{
                $t("message.Add_road_section")
              }}
            </div>
          </template>
        </a-tab-pane>
      </a-tabs>
      <div class="drawerOptionBox">
        <a-button @click="onClose">{{ $t("message.Cancel") }}</a-button>
        <a-button
          v-if="!disabled"
          style="margin-left: 8px"
          type="primary"
          @click="onSubmit"
        >
          {{ $t("message.Confirm") }}</a-button
        >
      </div>
    </a-drawer>
    <!--选择碳排因子弹窗-->
    <a-modal
      :visible="visible2"
      :width="1524"
      :title="$t('message.selective_carbon_emission_factor')"
      @cancel="handleCancel"
      @ok="handleOk2"
    >
      <yzChooseView v-if="visible2" @onselectedRows="onselectedRows" />
    </a-modal>
    <!--手动添加碳排因子弹窗-->
    <a-modal
      :visible="visible3"
      :width="1000"
      :title="$t('message.manually_add_carbon_emission_factors')"
      @cancel="handleCancel"
      @ok="handleOk3"
    >
      <yzAddView v-if="visible3" ref="yzAddView" />
    </a-modal>
  </div>
</template>

<script>
import { getAction, postAction } from "@/api/manage";
import { cloneObject } from "@/utils/util";
import yzCard from "@comp/common/yzCard2.vue";
import yzChooseView from "@comp/common/yzChooseView.vue";
import yzAddView from "@comp/common/yzAddView.vue";

export default {
  name: "inputAndOutputForm",
  components: {
    yzCard,
    yzChooseView,
    yzAddView,
  },
  props: {
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      visible: false,
      drawerTitle: "",
      activeKey: "1", // 1基础信息 2运输信息
      formObj: {
        transportList: [
          {
            selectedRows: {
              denominatorUnit: "",
            },
          },
        ], // 路段数据
        isTransport: false,
      },
      activeCollapseKey: ["0"],
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      flow_data_sourcesData: [], // 数据来源
      vehicle_codeData: [], // 交通工具
      unit_product_weightData: [], // 单位产品重量
      product_typeData: [], // 产品类型
      getAllUnitByGroupData: {}, // 单位分组数据
      // ===============================================================碳排因子
      cachesSlectedRows: {}, // 暂存碳排因子
      selectedRows: {
        denominatorUnit: "",
      },
      visible2: false, // 选择因子弹窗
      visible3: false, // 手动添加因子弹窗
      transportIndex: undefined,
      // ===============================================================碳排因子
      isAss: 1, //1新增2修改
      qianm:'km',
      emissionFactorId:''
    };
  },
  created() {},
  methods: {
    // ===============================================================碳排因子
    /**
     * 打开选择碳排因子弹窗
     * 手动添加碳排因子弹窗
     */
    handleAdd(type, transportIndex) {
      if (transportIndex !== undefined) {
        this.transportIndex = transportIndex;
      } else {
        this.transportIndex = undefined;
      }
      if (type == "chooseYZ") {
        // 选择因子
        this.visible2 = true;
      }
      if (type == "addYZ") {
        // 手动添加因子
        this.visible3 = true;
      }
    },
    /**
     * 选择因子
     * @param value
     */
    onselectedRows(value) {
      console.log("onselectedRows", value);
      if (this.transportIndex !== undefined) {
        // 运输路段-碳排因子
        this.formObj.transportList[this.transportIndex].cachesSlectedRows =
          value;
      } else {
        // 基本信息-碳排因子
        this.cachesSlectedRows = value;
      }
    },
    /**
     * 关闭选择碳排因子弹窗
     * 关闭手动添加碳排因子弹窗
     */
    handleCancel() {
      this.visible2 = false;
      this.visible3 = false;
    },
    /**
     * 选择碳排因子弹窗-确定
     */
    handleOk2() {
      if (this.transportIndex !== undefined) {
        // 运输路段-碳排因子
        let theObj = this.formObj.transportList[this.transportIndex];
        theObj.selectedRows = theObj.cachesSlectedRows;
        theObj.emissionFactorId = theObj.cachesSlectedRows.id;
        theObj.factorValue = theObj.cachesSlectedRows.factorValue;
        theObj.emissionFactorUnit = theObj.cachesSlectedRows.numeratorUnit;
        this.unitChange(
          "km",
          theObj.selectedRows.denominatorUnit,
          this.transportIndex
        );
      } else {
        // 基本信息-碳排因子
        this.selectedRows = this.cachesSlectedRows;
        this.formObj.emissionFactorId = this.cachesSlectedRows.id;
        this.formObj.factorValue = this.cachesSlectedRows.factorValue;
        this.formObj.emissionFactorUnit = this.cachesSlectedRows.numeratorUnit;
        this.unitChange(
          this.formObj.flowUnitName,
          this.selectedRows.denominatorUnit
        );
      }
      this.visible2 = false;
    },
    /**
     * 手动添加碳排因子弹窗-确定
     */
    handleOk3() {
      if (!this.$refs.yzAddView.checkFormData()) {
        return;
      }
      console.log("handleOk3", this.$refs.yzAddView.queryParam);
      postAction(
        "/emission/factor/cyEmissionFactor/addEmissionByCarbonCheck",
        this.$refs.yzAddView.queryParam
      ).then((res) => {
        if (res.success) {
          this.$message.success(this.$t("message.add_success"));
          console.log("listInfo formObj", this.activeKey);
          this.emissionFactorId = res.result;
          this.listInfo(2);
        }
      });
    },
    
    /**
     * 获取因子数据
     */
    listInfo(value) {
      console.log('emissionFactorId', this.formObj);
      getAction("/emission/factor/cyEmissionFactor/listInfo", {
        id: value==2?this.emissionFactorId:this.formObj.emissionFactorId,
      }).then((res) => {
        if (res.success) {
          let selectedRows = {
            id: res.result.emissionFactorObject.id,
            name: res.result.emissionFactorObject.name,
            model: res.result.emissionFactorObject.model,
            factorValue: res.result.emissionFactorDataObject.factorValue,
            numeratorUnit: res.result.emissionFactorDataObject.numeratorUnit,
            denominatorUnit:res.result.emissionFactorDataObject.denominatorUnit,
            releaseOrg: res.result.emissionFactorObject.releaseOrg,
            releaseYear: res.result.emissionFactorObject.releaseYear,
          };
          if (this.transportIndex !== undefined&&this.formObj.transportList.length>0) {
            // 运输路段-碳排因子
            let theObj = this.formObj.transportList[this.transportIndex];
            theObj.selectedRows = selectedRows;
            theObj.emissionFactorId = selectedRows.id;
            theObj.factorValue = selectedRows.factorValue;
            theObj.emissionFactorUnit = selectedRows.numeratorUnit;
            // this.unitChange('km', theObj.selectedRows.denominatorUnit, this.transportIndex)
          } else {
            // 基本信息-碳排因子
            this.selectedRows = selectedRows;
            this.formObj.emissionFactorId = selectedRows.id;
            this.formObj.factorValue = selectedRows.factorValue;
            this.formObj.emissionFactorUnit = selectedRows.numeratorUnit;
            // this.unitChange(this.formObj.flowUnitName, this.selectedRows.denominatorUnit)
          }
          this.$forceUpdate();
          console.log("listInfo formObj", this.formObj);
          console.log('selectedRows',this.selectedRows);
          this.visible3 = false;
          if(value==1){
            this.visible = true;
          }
        }
      });
    },
    /**
     * 编辑获取运输因子数据
     */
    listInfoSelectedRows(uid, index) {
      console.log("emissionFactorId", this.formObj);
      getAction("/emission/factor/cyEmissionFactor/listInfo", {
        id: uid,
      }).then((res) => {
        if (res.success) {
          let selectedRows = {
            id: res.result.emissionFactorObject.id,
            name: res.result.emissionFactorObject.name,
            model: res.result.emissionFactorObject.model,
            factorValue: res.result.emissionFactorDataObject.factorValue,
            numeratorUnit: res.result.emissionFactorDataObject.numeratorUnit,
            denominatorUnit:
              res.result.emissionFactorDataObject.denominatorUnit,
            releaseOrg: res.result.emissionFactorObject.releaseOrg,
            releaseYear: res.result.emissionFactorObject.releaseYear,
          };

          // 运输路段-碳排因子
          let theObj = this.formObj.transportList[index];
          theObj.selectedRows = selectedRows;
          theObj.emissionFactorId = selectedRows.id;
          theObj.factorValue = selectedRows.factorValue;
          theObj.emissionFactorUnit = selectedRows.numeratorUnit;
          // this.unitChange('km', theObj.selectedRows.denominatorUnit, index)
          console.log("listInfo formObj", this.formObj);
          this.visible3 = false;
        }
      });
    },
    listObjUpdate(value){
        if(this.formObj.transportList.length>0){
            this.formObj.transportList.forEach((item,index)=>{
              this.listInfoSelectedRows(item.emissionFactorId,index)
            })
            this.visible=true
        }else{
          this.visible=true
        }
        this.$forceUpdate()
    },
    // ===============================================================碳排因子
    onChangeIsTransport(e) {
      console.log(e);
      console.log(this.formObj);
      if (this.formObj.isTransport) {
        // 需要运输
        if (this.formObj.transportList.length <= 0) {
          this.formObj.transportList.push({
            selectedRows: {
              denominatorUnit: "",
            },
          });
        }
      } else {
        // 不需要运输
      }
    },
    /**
     * 切换tab
     * @param key 1基础信息 2运输信息
     */
    onChangeActiveKey(key) {
      console.log('onChangeActiveKey', key);
      this.activeKey = key
      if (this.formObj.transportList.length <= 0) {
          this.formObj.transportList.push({
            selectedRows: {
              denominatorUnit: "",
            },
          });
        }
    },
    /**
     * 检查表单数据
     */
    checkFormData() {
      // 基础信息
      if (!this.formObj.emissionSourceType) {
        // this.$message.warn('请选择基础信息-类型')
        this.$message.warn(
          this.$t("message.please_select_basic_information_type")
        );
        return false;
      }
      if (!this.formObj.emissionSourceName) {
        // this.$message.warn('请输入基础信息-名称')
        this.$message.warn(
          this.$t("message.please_enter_basic_information_name")
        );
        return false;
      }
      // if (!this.formObj.flowNumber) {
      //   // this.$message.warn('请输入基础信息-数量')
      //   this.$message.warn(this.$t('message.please_enter_basic_information_quantity'))
      //   return false
      // }
      if (!this.formObj.emissionSourceUnit) {
        // this.$message.warn('请选择基础信息-单位')
        this.$message.warn(
          this.$t("message.please_select_basic_information_unit")
        );
        return false;
      }
      if (!this.formObj.dataSources) {
        // this.$message.warn('请选择基础信息-数据来源')
        this.$message.warn(
          this.$t("message.please_select_basic_information_data_source")
        );
        return false;
      }
      if (!this.formObj.emissionFactorId) {
        // this.$message.warn('请选择基础信息-碳排因子')
        this.$message.warn(
          this.$t(
            "message.please_select_basic_information_carbon_emission_factor"
          )
        );
        return false;
      }
      if (!this.formObj.factorRatio) {
        // this.$message.warn('请输入基础信息-单位比例换算')
        this.$message.warn(
          this.$t(
            "message.please_enter_basic_information_unit_scale_conversion"
          )
        );
        return false;
      }
      // 运输信息
      if (this.formObj.isTransport) {
        // if (!this.formObj.weight) {
        //   // this.$message.warn('请输入运输信息-货物重量')
        //   this.$message.warn(this.$t('message.please_enter_shipping_information_cargo_weight'))
        //   return false
        // }
        if (!this.formObj.weightUnit) {
          // this.$message.warn('请选择运输信息-货物重量单位')
          this.$message.warn(
            this.$t(
              "message.please_select_transportation_information_cargo_weight_unit"
            )
          );
          return false;
        }
        let errName = null;
        let errIndex = null;
        for (let i = 0; i < this.formObj.transportList.length; i++) {
          let obj = this.formObj.transportList[i]
          // if (!obj.origin) {
          //   errIndex = i
          //   // errName = '请输入运输信息-路段始发地'
          //   errName = this.$t('message.please_enter_the_transportation_information_the_origin_of_the_section')
          //   break
          // }
          // if (!obj.destination) {
          //   errIndex = i
          //   // errName = '请输入运输信息-路段目的地'
          //   errName = this.$t('message.please_enter_transportation_information_section_destination')
          //   break
          // }
          // if (!obj.distance) {
          //   errIndex = i
          //   // errName = '请输入运输信息-路段距离（km）'
          //   errName = this.$t('message.please_enter_transportation_information_link_distance')
          //   break
          // }
          if (!obj.vehicleId) {
            errIndex = i
            // errName = '请选择运输信息-路段交通工具'
            errName = this.$t('message.please_select_transportation_information_section_transportation')
            break
          }
          if (!obj.emissionFactorId) {
            errIndex = i
            // errName = '请选择运输信息-路段排放因子'
            errName = this.$t('message.please_select_transportation_information_link_emission_factor')
            break
          }
          if (!obj.factorRatio) {
            errIndex = i
            // errName = '请选择运输信息-单位比例换算'
            errName = this.$t('message.please_select_transportation_information_company_proportion_conversion')
            break
          }
        }
        if (errIndex !== null) {
          this.$message.warn(`${errName}`);
          return false;
        }
      }
      return true;
    },
    /**
     * 提交数据
     */
    onSubmit() {
      console.log("onSubmit", this.formObj);
      console.log("this.isAss ", this.isAss );
      if (this.checkFormData()) {
        let reqData = cloneObject(this.formObj);
        if (!reqData.isTransport) {
          // 不需要运输，清除运输数据
          reqData.weight = 0;
          delete reqData.weightUnit;
          delete reqData.transportList;
        } else {
          // 需要运输，清除多余数据
          reqData.transportList.forEach((item) => {
            delete item.cachesSlectedRows;
            delete item.selectedRows;
          });
        }
        console.log("saveFlow reqData", reqData);

        if (this.isAss == 1) {
          postAction(
            "/CyEmissionSourceLibrary/cyEmissionSourceLibrary/add",
            reqData
          ).then((res) => {
            if (res.success) {
              this.$message.success(res.message);
              this.$emit("back");
              this.onClose();
            }else{
              this.$message.error(res.message);
            }
          });
        } else {
          postAction(
            "/CyEmissionSourceLibrary/cyEmissionSourceLibrary/edit",
            reqData
          ).then((res) => {
            if (res.success) {
              this.$message.success(res.message);
              this.$emit("back");
              this.onClose();
            }
          });
        }


      }
    },
    getData() {
      console.log("inputAndOutputForm getData");

      // 数据来源
      getAction("/sys/api/getDictItems", {
        dictCode: "flow_data_sources",
      }).then((res) => {
        this.flow_data_sourcesData = res || [];
        console.log("getDictItems flow_data_sources =>", res);
      });
      // 交通工具
      getAction("/sys/api/getDictItems", {
        dictCode: "vehicle_code",
      }).then((res) => {
        this.vehicle_codeData = res || [];
        console.log("getDictItems vehicle_code =>", res);
      });
      // 单位产品重量
      // getAction('/sys/api/getDictItems', {
      //   dictCode: 'unit_product_weight'
      // }).then((res) => {

      //   console.log('getDictItems unit_product_weight =>', res)
      // });
      getAction("/emission/factor/cyEmissionUnit/getAllUnit").then((res) => {
        if (res.success) {
          this.unit_product_weightData = res.result || [];
        }
      });
      // 单位
      getAction("/emission/factor/cyEmissionUnit/getAllUnitByGroup").then(
        (res) => {
          if (res.success) {
            this.getAllUnitByGroupData = res.result || {};
          }
        }
      );
      // 产品类型
      getAction("/sys/api/getDictItems", {
        dictCode: "product_type",
      }).then((res) => {
        this.product_typeData = res || [];
        console.log("getDictItems product_type =>", res);
      });
      this.$forceUpdate();
    },
    // ==========================================================基础信息
    /**
     * 修改基础信息-类型
     */
    onChangeFlowType(value) {
      console.log("onChangeFlowType", value);
      let theIndex = this.product_typeData.findIndex(
        (ele) => ele.value == value
      );
      if (theIndex > -1) {
        this.$set(
          this.formObj,
          "emissionSourceTypeName",
          this.product_typeData[theIndex].text
        );
      }
    },
    /**
     * 修改基础信息-单位
     */
    onChangeFlowUnit(e) {
      console.log("onChangeFlowUnit", e, this.getAllUnitByGroupData);
      for (let key in this.getAllUnitByGroupData) {
        let value = this.getAllUnitByGroupData[key];
        for (let index = 0; index < value.length; index++) {
          if (value[index].id == e) {
            this.$set(
              this.formObj,
              "emissionSourceUnitName",
              value[index].unitCode
            );
            this.unitChange(
              this.formObj.flowUnitName,
              this.selectedRows.denominatorUnit
            );
          }
        }
      }
      console.log("onChangeFlowUnit", this.formObj);
    },
    /**
     * 修改基础信息-数据来源
     */
    onChangeFlowDataSources(value) {
      console.log("onChangeFlowDataSources", value);
      let theIndex = this.flow_data_sourcesData.findIndex(
        (ele) => ele.value == value
      );
      if (theIndex > -1) {
        this.$set(
          this.formObj,
          "dataSourcesName",
          this.flow_data_sourcesData[theIndex].text
        );
      }
    },
    // ==========================================================运输信息
    /**
     * 修改重量单位
     */
    onChangeWeightUnit(value) {
      console.log("onChangeWeightUnit", value);
      let theIndex = this.unit_product_weightData.findIndex(
        (ele) => ele.id == value
      );
      console.log("onChangeWeightUnit", theIndex);

      if (theIndex > -1) {
        this.$set(
          this.formObj,
          "weightUnitName",
          this.unit_product_weightData[theIndex].unitCode
        );
        this.$forceUpdate();
      }
    },
    /**
     * 修改交通工具
     */
    onChangeVehicleId(value, transportItem) {
      console.log("onChangeVehicleId", value, this.vehicle_codeData);
      let theIndex = this.vehicle_codeData.findIndex(
        (ele) => ele.value == value
      );
      if (theIndex > -1) {
        this.$set(
          transportItem,
          "vehicleName",
          this.vehicle_codeData[theIndex].text
        );
      }
    },
    /**
     * 添加路段
     */
    onAddTransport() {
      this.formObj.transportList.push({
        selectedRows: {},
      });
      let data1 = this.formObj.transportList.length - 1;
      this.activeCollapseKey.push(String(data1));
      console.log("onAddTransport", this.activeCollapseKey);
    },
    /**
     * 删除路段
     * @param transportIndex
     */
    onDelTransport(transportIndex) {
      this.formObj.transportList.splice(transportIndex, 1);
    },

    unitChange(sourceUnit, targetUnit, transportIndex) {
      console.log("unitChange", sourceUnit, targetUnit, transportIndex);
      if (sourceUnit && targetUnit) {
        if (sourceUnit == targetUnit) {
          this.$set(this.formObj, "factorRatio", 1);
        } else {
          getAction("/emission/factor/cyEmissionFactor/api/getConvertValue", {
            sourceUnit,
            targetUnit,
          }).then((res) => {
            if (res.success) {
              if (transportIndex !== undefined) {
                this.$set(
                  this.formObj.transportList[transportIndex],
                  "factorRatio",
                  res.result
                );
              } else {
                this.$set(this.formObj, "factorRatio", res.result);
              }
            }
          });
        }
      }
    },
    // ==============================================================================
    /**
     * 下拉框数据过滤
     */
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    /**
     * 关闭抽屉，初始化数据
     */
    onClose() {
      this.formObj = {
        transportList: [
          {
            selectedRows: {},
          },
        ], // 路段数据
        isTransport: false,
      };
      this.selectedRows = {};
      this.visible = false;
    },
  },
};
</script>

<style lang="less" scoped>
.fleWarp{
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  flex: 1;
}
.flexs{
  display: flex;
  align-items: center;
  gap:24px;
}

.textse {
  font-weight: 400;
  font-size: 12px;
  color: rgba(0, 0, 0, 0.4);
}
.butons {
  display: inline-flex;
  align-items: center;
  background: #ffffff;
  border-radius: 3px 3px 3px 3px;
  border: 1px solid #dcdcdc;
  font-weight: 400;
  font-size: 14px;
  color: #148958;
  padding: 5px 16px;
  img {
    width: 16px;
    height: 16px;
    margin-right: 8px;
  }
}

/deep/ .ant-collapse-content > .ant-collapse-content-box {
  padding: 16px 24px 0;
  overflow: hidden;
}

/deep/ .ant-collapse > .ant-collapse-item {
  border-bottom: none;
}

/deep/ .ant-collapse {
  background: #fff;
}

/deep/ .ant-collapse-item {
  margin-bottom: 16px;
}

/deep/ .ant-collapse-header {
  background: #f5f7f6;
}

/deep/ .ant-collapse-content {
  background: #f5f7f6;
}

/deep/ .ant-collapse-content-box {
  background: #f5f7f6;
}

.box1 {
  display: flex;
  align-items: center;

  .box1_text1 {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: #333333;
    transform: translateY(2px);
  }

  .box1_text2 {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 12px;
    color: #888888;
  }

  .box1_text3 {
    margin: 0 4px;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: #333333;
  }
}

.collapseIcon {
  width: 16px;
  height: 16px;
}

.addBtn {
  margin-top: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  width: fit-content;
  padding: 5px 16px;
  background: #ffffff;
  border-radius: 3px;
  border: 1px solid #148958;
  font-family: PingFang SC, PingFang SC;
  font-weight: 400;
  font-size: 14px;
  color: #148958;

  .addBtn_icon {
    width: 16px;
    height: 16px;
  }
}

.tianjia {
  width: 380px;
  height: 156px;
  background: #f8f8f8;
  border-radius: 3px 3px 3px 3px;
  border: 1px solid #d9d9d9;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  .color {
    color: #888888;
  }

  .leftShoudong {
    background: #fff !important;
    border-color: #148958 !important;
    color: #148958 !important;
  }

  .leftChaxun {
    margin-left: 16px;
    background: #148958 !important;
    color: #fff !important;
  }

  .leftChaxun:hover {
    background: #148958 !important;
    color: #fff !important;
  }
}

.manual {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 15px;

  .manualOperation {
    background: #ffffff;
    border-radius: 3px 3px 3px 3px;
    font-weight: 400;
    font-size: 12px;
    color: #148958;
    line-height: 0;
    border: 1px solid #148958;
    padding: 4px 8px;
    display: flex;
    align-items: center;

    img {
      width: 14px;
      height: 14px;
      margin-right: 8px;
    }
  }
}

.drawerOptionBox {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e9e9e9;
  padding: 10px 16px;
  background: #fff;
  text-align: right;
  z-index: 12;
}
</style>
